package com.masterclient.app.modules.pay.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.baselib.utils.notify.RxBus;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.eoner.baselibrary.bean.order.PayResult;
import com.masterclient.app.modules.pay.contract.PayContract;
import com.masterclient.app.modules.pay.contract.PayPresenter;
import com.eoner.baselibrary.bean.pay.AliPayInfoBean;
import com.eoner.baselibrary.bean.pay.PaymentInfoBean;
import com.eoner.baselibrary.bean.pay.PaymentModule;
import com.eoner.baselibrary.bean.pay.WechatPayInfoBean;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.Utils;
import com.masterclient.app.widget.TitlebarView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

@Route(path = AroutePath.PAY_ACTIVITY)
public class PayActivity extends BaseActivity<PayPresenter> implements PayContract.View{

    @BindView(R.id.title_view)
    TitlebarView title_view;
    @BindView(R.id.checkBox_wx)
    CheckBox checkBox_wx;
    @BindView(R.id.checkBox_zfb)
    CheckBox checkBox_zfb;

    @BindView(R.id.tv_actual_price)
    TextView tv_actual_price;

    @BindView(R.id.alipay_layout)
    View alipay_layout;
    @BindView(R.id.view_pay_line)
    View view_pay_line;
    @BindView(R.id.rl_wxpay)
    View rl_wxpay;


    @BindView(R.id.wechat_icon)
    ImageView wechat_icon;
    @BindView(R.id.wechat_tag)
    TextView wechat_tag;
    @BindView(R.id.wechat_desc)
    TextView wechat_desc;
    @BindView(R.id.ali_icon)
    ImageView ali_icon;
    @BindView(R.id.ali_tag)
    TextView ali_tag;
    @BindView(R.id.ali_desc)
    TextView ali_desc;

    @Autowired(name = "pay_amount")
    int pay_amount;
    @Autowired(name = "pay_order_no")
    String pay_order_no;
    @Autowired(name = "channel")
    String channel;
    @Autowired(name = "user_id")
    String user_id;
    @Autowired(name = "redirect_url")
    String redirect_url;
    @Autowired(name = "payback_url")
    String payback_url;
    @Autowired(name = "time_expire")
    String time_expire;

    IWXAPI iwxapi;
    RxBus rxBus;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_activity);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);



        //channel = "zhenlv";

        iwxapi = WXAPIFactory.createWXAPI(mContext, null);
        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.PAY_RESULT), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                String result = (String) o;
                switch (result) {
                    case Config.PAY_SUCCESS://支付成功
                        pay_success();
                        break;
                    case Config.PAY_FAILED://支付失败
                        has_click_pay = false;
                        showToast("支付失败，请重新支付");
                        finish();
                        break;
                }
            }
        });

        add_listener();

    }

    private void pay_success() {
        showToast("支付成功");
        Intent intent = new Intent(this, BridgeActivity.class);
        intent.putExtra("url",redirect_url);
        startActivity(intent);
        finish();
    }

    private void add_listener() {
        title_view.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });


        checkBox_zfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkBox_wx.setChecked(false);
                }
            }
        });

        checkBox_wx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkBox_zfb.setChecked(false);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.get_payment_info(pay_amount,channel,pay_order_no,user_id);
    }




    boolean has_click_pay = false;
    @OnClick({R.id.pay_btn,R.id.rl_wxpay,R.id.alipay_layout}) void onClick(View view){
        switch (view.getId()){
            case R.id.pay_btn:
                if(checkBox_zfb.isChecked()){
                    mPresenter.get_alipay_prepay(channel,pay_order_no);
                }else if(checkBox_wx.isChecked()){
                    mPresenter.get_wx_prepay(channel,pay_order_no);
                }
                break;
            case R.id.rl_wxpay:
                checkBox_wx.setChecked(true);
                break;
            case R.id.alipay_layout:
                checkBox_zfb.setChecked(true);
                break;
        }
    }

    String order_no;
    @Override
    public void get_payment_info_success(PaymentInfoBean bean) {

        if(bean.getData() != null){
            order_no = bean.getData().getOrder_no();
            Utils.set_price_style1(tv_actual_price, "¥ " + bean.getData().getShould_pay_total());
            List<PaymentModule> paymentModules = bean.getData().getPayment_module();
            for(PaymentModule paymentModule : paymentModules){
                if("1".equals(paymentModule.getId())){
                    alipay_layout.setVisibility(View.VISIBLE);
                    ali_tag.setText(paymentModule.getName());
                    ali_desc.setText(paymentModule.getDescription());
                    GlideUtil.displayImage(PayActivity.this,paymentModule.getLogo(),ali_icon,R.mipmap.defaults);
                }
                if("2".equals(paymentModule.getId())){
                    rl_wxpay.setVisibility(View.VISIBLE);
                    view_pay_line.setVisibility(View.VISIBLE);
                    wechat_tag.setText(paymentModule.getName());
                    wechat_desc.setText(paymentModule.getDescription());
                    GlideUtil.displayImage(PayActivity.this,paymentModule.getLogo(),wechat_icon,R.mipmap.defaults);
                }
            }
            if(!"0".equals(bean.getData().getOrder_status())){
                pay_success();
            }
        }

    }

    @Override
    public void get_payment_info_failed(String msg) {
        showToast(msg);
    }

    @Override
    public void get_wx_prepay_success(WechatPayInfoBean bean) {

        WechatPayInfoBean.DataBean dataBean = bean.getData();
        if(dataBean != null){
            has_click_pay = true;
            iwxapi.registerApp(dataBean.getAppid());
            PayReq payReq = new PayReq();
            Config.APP_ID = dataBean.getAppid();
            payReq.appId = dataBean.getAppid();
            payReq.nonceStr = dataBean.getNoncestr();
            payReq.packageValue = dataBean.getWx_package();
            payReq.partnerId = dataBean.getPartnerid();
            payReq.prepayId = dataBean.getPrepayid();
            payReq.timeStamp = dataBean.getTimestamp();
            payReq.sign = dataBean.getSign();
            iwxapi.sendReq(payReq);
        }
    }

    @Override
    public void get_wx_prepay_failed(String msg) {

    }

    private static final int SDK_PAY_FLAG = 1;
    @Override
    public void get_alipay_prepay_uccess(AliPayInfoBean bean) {
        AliPayInfoBean.DataBean dataBean = bean.getData();
        if(dataBean == null){
            return;
        }
        has_click_pay = true;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(dataBean.getRequestUrl(), true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void get_alipay_prepay_failed(String msg) {

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        pay_success();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。 支付失败
                        has_click_pay = false;
                        showToast("支付失败，请重新支付");
                        finish();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

}
